<?php

class login extends FModel
{
    public function __construct()
    {
        parent::__construct('login');
        
        $this->controller->setTable('usuarios');
    }
    
    public function getForm()
    {
        $form = new frmLogin();
        
        return $form;
    }
    
    public function login($args)
    {
        $controller = new usuarioController();
        $controller->setLogin($args['usuario']);
        $controller->setSenha($args['senha']);
        
        $search = $controller->search();

        $response = new FJSONResponse();
        if ( $search[0]['login'] == $args['usuario'] )
        {
            $response->setSuccess(true);
            $response->setCloseForm(true);
            $response->setAction(FUtil::getReloadPageAction());
            
            $login = new FLogin();
            $login->setLogin($search[0]['login']);
            $login->setName($search[0]['nome']);
            $login->setAccessTime(date('d/m/Y H:i'));
            
            $session = new FSessionManager('login');
            $session->setData($login);
        }
        else 
        {
            $response->setSuccess(false);
            $response->setMsg('O usuário ou a senha informados está incorreto!');
        }
        
        return $response;
    }
    
    public function logout($args)
    {
        $session = new FSessionManager('login');
        $response = new FJSONResponse();
        
        $login = $session->getData();
        if ( $login instanceof FLogin )
        {                        
            $response->setConfirmOnClose(true);
            $response->setOnCloseConfirmMsg($login->getName() . ', tem certeza que deseja sair do sistema?');
            
            $ajaxRequest = new FAjaxRequest('login', 'logoutConfirmed', FUtil::getReloadPageAction());
            
            $response->setAction($ajaxRequest->generate());
        }
        else
        {
            $response->setAction(FUtil::getReloadPageAction());
        }
        
        return $response;
    }
    
    public function logoutConfirmed()
    {
        $session = new FSessionManager('login');
        $session->setData(NULL);
        
        $response = new FJSONResponse();
        $response->setShowSuccessMsg(true);
        $response->setMsg('Logout efetuado com sucesso!');
        
        return $response;
    }
}

?>
